<?php
// +----------------------------------------------------------------------
// | 中联致远服务端框架
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.zhongliansoft.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: tony <tanyu@zhongliansoft.com>
// +----------------------------------------------------------------------

namespace app\common\model;
use think\Validate;
use think\model\concern\SoftDelete;
use think\facade\Log;

class BookPlan extends Common
{
    protected $rule = [
        'plan_book_num'=> 'require|number',
    ];

    protected $msg = [
        'plan_book_num.require' => '请输入教材数量',
        'plan_book_num.number' => '教材数量必须是数字',
    ];

    /**
     * 设置csv header
     * @return array
     */
    public function csvHeader()
    {
        return [
            [
                'id'   => 'plan_year',
                'desc' => '年度',
            ],
            [
                'id'   => 'plan_season',
                'desc' => '季度',
            ],
            [
                'id'   => 'grade',
                'desc' => '年级',
            ],
            [
                'id'   => 'degree',
                'desc' => '层次',
            ],
            [
                'id'   => 'bmmc',
                'desc' => '院系',
            ],
            [
                'id'   => 'zymc',
                'desc' => '专业名称',
            ],
            [
                'id'   => 'dir',
                'desc' => '方向',
            ],
            [
                'id'   => 'course_name',
                'desc' => '课程名称',
            ],
            [
                'id'   => 'book_name',
                'desc' => '教材名称',
            ],
            [
                'id'   => 'book_author',
                'desc' => '主编',
            ],
            [
                'id'   => 'book_concern',
                'desc' => '出版社',
            ],
            [
                'id'   => 'book_isbn',
                'desc' => 'ISBN书号',
            ],
            [
                'id'   => 'book_edition',
                'desc' => '版次',
            ],
            [
                'id'   => 'book_date',
                'desc' => '出版年限',
            ],
            [
                'id'   => 'plan_student',
                'desc' => '学生数量',
            ],
            [
                'id'   => 'plan_book_num',
                'desc' => '教材数量',
            ],
            [
                'id'   => 'book_reward',
                'desc' => '获奖情况',
            ],
            [
                'id'   => 'description',
                'desc' => '备注',
            ]
        ];
    }

    /**
     * 设置教材定价 csv header
     * @return array
     */
    public function csvPriceHeader()
    {
        return [
            [
                'id'   => 'book_isbn',
                'desc' => 'ISBN书号',
            ],
            [
                'id'   => 'book_edition',
                'desc' => '版次',
            ],
            [
                'id'   => 'book_date',
                'desc' => '出版年限',
            ],
            [
                'id'   => 'plan_year',
                'desc' => '年度',
            ],
            [
                'id'   => 'plan_season',
                'desc' => '季度',
            ],
            [
                'id'   => 'book_price',
                'desc' => '单价',
            ]
        ];
    }

    /**
     * @param $post
     *
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function tableData($post)
    {
        if(isset($post['limit'])){
            $limit = $post['limit'];
        }else{
            $limit = config('paginate.list_rows');
        }

        $tableWhere = $this->tableWhere($post);
        $list = $this->alias('plan')
                ->field("plan.id, plan.plan_year, case when plan.plan_season = 1 then '春季' when plan.plan_season = 3 then '秋季' end plan_season, 
                    bm.bmmc as dept_name, zy.zymc as specialty_name, plan.plan_class_name, 
                    case when plan.plan_dir = 1 then '就业' when plan.plan_dir = 2 then '升学' when plan.plan_dir = 3 then '创业' end plan_dir,
                    plan.course_name, book.book_name, book.book_author, book.book_concern, book.book_isbn, plan.plan_price, plan.book_disc, plan.plan_student, plan.plan_book_num, mgr.username, plan.plan_date")
                ->join('zlzhsf.pbmdm bm', 'bm.bmdm = plan.plan_dep_id')
                ->join('zlzhsf.pzydm zy', 'zy.zydm = plan.plan_specialty_id')
                ->join('zl_book_info book', 'book.id = plan.plan_book_id')
                ->join('zl_manage mgr', 'mgr.id = plan.plan_operid')
                ->where($tableWhere['where'])->order($tableWhere['order'])->paginate($limit);
        $data = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型

        $re['code'] = 0;
        $re['msg'] = '';
        $re['count'] = $list->total();
        $re['data'] = $data;

        return $re;
    }

    //where搜索条件
    protected function tableWhere($post)
    {
        $where = [];
        if(isset($post['plan_code']) && $post['plan_code'] != ""){
            $where[] = ['plan.plan_code', 'eq', $post['plan_code']];
        }
        if(isset($post['year']) && $post['year'] != ""){
            $where[] = ['plan.plan_year', 'eq', $post['year']];
        }
        if(isset($post['season']) && $post['season'] != ""){
            $where[] = ['plan.plan_season', 'eq', $post['season']];
        }
        if(isset($post['dep_id']) && $post['dep_id'] != ""){
            $where[] = ['plan.plan_dep_id', 'eq', $post['dep_id']];
        }
        if(isset($post['specialty_id']) && $post['specialty_id'] != ""){
            $where[] = ['plan.plan_specialty_id', 'eq', $post['specialty_id']];
        }
        if(isset($post['class_id']) && $post['class_id'] != ""){
            $where[] = ['plan.plan_code', 'eq', $post['class_id']];
        }
        if(isset($post['dir']) && $post['dir'] != ""){
            $where[] = ['plan.plan_dir', 'eq', $post['dir']];
        }
        if(isset($post['book_name']) && $post['book_name'] != ""){
            $where[] = ['book.book_name', 'like', '%' . $post['book_name'] . '%'];
        }

        $result['where'] = $where;
        $result['field'] = "*";
        $result['order'] = ['id ASC'];
        return $result;
    }


    /**
     * @param $list
     *
     * @return mixed
     */
    protected function tableFormat($list)
    {
        return $list;
    }

    /**
     * 获取csv数据
     * @param $post
     * @return array
     */
    public function getBookPlanById($id)
    {
        return $this->alias('plan')
        ->field("plan.id, plan.plan_code, plan.plan_year, case when plan.plan_season = 1 then '春季' when plan.plan_season = 3 then '秋季' end plan_season, 
            bm.bmmc as dept_name, zy.zymc as specialty_name, plan.plan_class_name, 
            case when plan.plan_dir = 1 then '就业' when plan.plan_dir = 2 then '升学' when plan.plan_dir = 3 then '创业' end plan_dir,
            plan.course_name, book.book_name, book.book_author, book.book_concern, book.book_isbn, plan.plan_price, plan.book_disc, plan.plan_student, plan.plan_book_num, mgr.username, plan.plan_date")
        ->join('zlzhsf.pbmdm bm', 'bm.bmdm = plan.plan_dep_id')
        ->join('zlzhsf.pzydm zy', 'zy.zydm = plan.plan_specialty_id')
        ->join('zl_book_info book', 'book.id = plan.plan_book_id')
        ->join('zl_manage mgr', 'mgr.id = plan.plan_operid')
        ->where(['plan.id' => $id])->find(); 
    }

    /**
     * 获取csv数据
     * @param $post
     * @return array
     */
    public function getBookPlanExportData($post)
    {
        $result   = [
            'status' => false,
            'data'   => [],
            'msg'    => '无可导出用户'
        ]; 
 
        $tableWhere = $this->tableWhere($post);
        $list = $this->alias('plan')
                ->field("plan.id, plan.plan_year, case when plan.plan_season = 1 then '春季' when plan.plan_season = 3 then '秋季' end plan_season, 
                    bm.bmmc as dept_name, zy.zymc as specialty_name, plan.plan_class_name, 
                    case when plan.plan_dir = 1 then '就业' when plan.plan_dir = 2 then '升学' when plan.plan_dir = 3 then '创业' end plan_dir,
                    plan.course_name, book.book_name, book.book_author, book.book_concern, book.book_isbn, plan.plan_price, plan.book_disc, plan.plan_book_num, plan.plan_student, mgr.username, plan.plan_date")
                ->join('zlzhsf.pbmdm bm', 'bm.bmdm = plan.plan_dep_id')
                ->join('zlzhsf.pzydm zy', 'zy.zydm = plan.plan_specialty_id')
                ->join('zl_book_info book', 'book.id = plan.plan_book_id')
                ->join('zl_manage mgr', 'mgr.id = plan.plan_operid')
                ->where($tableWhere['where'])->select()->toArray();

        if (count($list) > 0) {
            $result['status'] = true;
            $result['msg']    = '导出成功';
            $result['data']   = $list;
            return $result;
        } else {
            //失败，导出失败
            return $result;
        }
    }
    
    /**
     * 修改计划
     * @param $data
     * @return array
     */
    public function edit($data)
    {
        $return = [
            'status' => false,
            'msg'    => '修改失败',
            'data'   => ''
        ];

        // 特殊情况处理
        //校验数据
        $validate = new Validate($this->rule, $this->msg);
        if (!$validate->check($data)) {
            $return['msg'] = $validate->getError();
            return $return;
        } 
       
        // if($data['plan_price'] <= 0) {
        //     $return['msg'] = '请输入合法的单价';
        //     return $return;
        // }
        if($data['plan_book_num'] <= 0) {
            $return['msg'] = '请输入合法的数量';
            return $return;
        }

        $where[]             = ['id', 'eq', $data['id']];
        $newData['plan_price'] = $data['plan_price'];
        $newData['book_disc'] = $data['book_disc'];
        $newData['plan_book_num'] = $data['plan_book_num'];
        $newData['course_name'] = $data['course_name'];
        $newData['plan_date'] = date('Y-m-d H:i:s', time());
        $result              = $this->save($newData, $where);
        
        $return['data']      = $result;
        $return['status'] = true;
        $return['msg']    = '修改成功'; 

        \think\facade\Request::token('__ZlServer_Token__', 'sha1'); 
        return $return;
    }

    
    /**
     * 复制计划
     * @param $data
     * @return array
     */
    public function copy($data)
    {
        $return = [
            'status' => false,
            'msg'    => '复制失败',
            'data'   => ''
        ];

        // 特殊情况处理
        //校验数据
        $validate = new Validate($this->rule, $this->msg);
        if (!$validate->check($data)) {
            $return['msg'] = $validate->getError();
            return $return;
        } 
        
        // 判断是否有重复数据
        $plan_book_info = $this->where(['plan_code' =>$data['plan_code'], 'plan_book_id' => $data['target_book_id']])->find();
        if($plan_book_info) {
            $return['msg'] = '该计划已存在此教材！';
            return $return;
        }

        // if($data['plan_price'] <= 0) {
        //     $return['msg'] = '请输入合法的单价';
        //     return $return;
        // }
        if($data['plan_book_num'] <= 0) {
            $return['msg'] = '请输入合法的数量';
            return $return;
        }

        // 查询自己负责的记录
        $model = new Common();
        $model->query("call copyBookPlan('".$data['plan_code']."','".$data['src_book_id']."','".$data['target_book_id']."','".$data['plan_price']."','".$data['book_disc']."','".$data['plan_book_num']."','".$data['target_course_name']."');");
        
        $return['data']   = [];
        $return['status'] = true;
        $return['msg']    = '复制成功'; 

        \think\facade\Request::token('__ZlServer_Token__', 'sha1'); 
        return $return;
    }
    
    /**
     * @param $list
     *
     * @return mixed
     */
    public function getKeyList()
    {
        $list = $this->alias('plan')
            ->field("concat(bm.bmmc, '-', zy.zymc, '-', plan.plan_grade, '-', plan.plan_degree_name, '-', 
                case when plan.plan_dir = 1 then '就业' when plan.plan_dir = 2 then '升学' when plan.plan_dir = 3 then '创业' end, '-',
                plan.plan_year, '-', case when plan.plan_season = 1 then '春季' when plan.plan_season = 3 then '秋季' end, '-', book.book_isbn) as keyName")
            ->join('zlzhsf.pbmdm bm', 'bm.bmdm = plan.plan_dep_id')
            ->join('zlzhsf.pzydm zy', 'zy.zydm = plan.plan_specialty_id')
            ->join('zl_book_info book', 'book.id = plan.plan_book_id')
            ->join('zl_manage mgr', 'mgr.id = plan.plan_operid')->select()->toArray();
 
        $nameList = [];
        foreach ($list as $key => $val) {
            $nameList[] = $val['keyName'];
        }
        
        return $nameList;
    }

    /**
     * @param $list
     *
     * @return mixed
     */
    public function getStudentNumList()
    {
        $list = $this->alias('plan')
            ->field("concat(bm.bmmc, '-', zy.zymc, '-', plan.plan_grade, '-', plan.plan_degree_name, '-', 
                case when plan.plan_dir = 1 then '就业' when plan.plan_dir = 2 then '升学' when plan.plan_dir = 3 then '创业' end, '-',
                plan.plan_year, '-', case when plan.plan_season = 1 then '春季' when plan.plan_season = 3 then '秋季' end) as keyName, plan_student")
            ->distinct(true)
            ->join('zlzhsf.pbmdm bm', 'bm.bmdm = plan.plan_dep_id')
            ->join('zlzhsf.pzydm zy', 'zy.zydm = plan.plan_specialty_id')
            ->join('zl_book_info book', 'book.id = plan.plan_book_id')
            ->join('zl_manage mgr', 'mgr.id = plan.plan_operid')->select()->toArray();
 
        $nameList = [];
        foreach ($list as $key => $val) {
            $nameList[$val['keyName']] = $val['plan_student'];
        }
        
        return $nameList;
    }
    
    /**
     * 获取年级信息
     * @return array|mixed
     */
    public function getGradeList()
    {
        // 默认值 
        return $this->distinct('true')->field('plan_grade')->order('plan_grade desc')->select();
    }
    
    /**
     * 获取层次信息
     * @return array|mixed
     */
    public function getDegreeList()
    {
        // 默认值
        return $this->distinct('true')->field('plan_degree_id, plan_degree_name')->order('plan_degree_id')->select(); 
    }

}